package com.xcx.services.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xcx.bo.DouyinCollect;
import com.xcx.bo.DouyinCollectExample;
import com.xcx.bo.DouyinUserInfo;
import com.xcx.bo.DouyinUserInfoExample;
import com.xcx.common.dto.base.BaseDto;
import com.xcx.common.dto.base.BaseResp;
import com.xcx.common.dto.req.SaveUserInfoReq;
import com.xcx.common.dto.req.UserLoginReq;
import com.xcx.common.dto.resp.UserLoginResp;
import com.xcx.common.enums.IsValidEnum;
import com.xcx.common.enums.ProductCodeEnum;
import com.xcx.common.enums.RespCodeEnum;
import com.xcx.common.exceptions.CommonException;
import com.xcx.common.services.DouyinService;
import com.xcx.common.services.common.CommUserService;
import com.xcx.common.utils.CheckParamUtils;
import com.xcx.common.utils.ExceptionUtils;
import com.xcx.common.utils.IdGenUtils;
import com.xcx.dao.DouyinCollectDao;
import com.xcx.dao.DouyinTempUserDao;
import com.xcx.dao.DouyinUserInfoDao;
import com.xcx.dto.CancelCollectUserReq;
import com.xcx.dto.CollectUserReq;
import com.xcx.dto.QueryCollectUserReq;
import com.xcx.dto.QueryVideoListReq;
import com.xcx.dto.QueryVideoListResp;
import com.xcx.enums.CollectStatusEnum;

import lombok.extern.slf4j.Slf4j;


/**
 * 抖音服务层
 */
@Slf4j
@Service
public class DouyinServiceImpl implements DouyinService {


    @Value("${wx.appId}")
    private String wxAppId;

    @Value("${wx.appSecret}")
    private String wxAppSecret;

    @Reference
    private CommUserService commUserService;

    @Resource
    private DouyinUserInfoDao douyinUserInfoDao;

    @Resource
    private DouyinTempUserDao douyinTempUserDao;
    
    @Resource
    private DouyinCollectDao douyinCollectDao;

    /**
     * 查询视频列表
     *
     * @param reqStr
     * @return
     */
    @Override
    public String queryVideoList(String reqStr) {
        log.info("queryVideoList.req:{}", reqStr);
        QueryVideoListResp baseResp = new QueryVideoListResp();

        try {
            CheckParamUtils.validateReqString(reqStr);
            QueryVideoListReq baseReq = BaseDto.fromJson(reqStr, QueryVideoListReq.class);
            CheckParamUtils.validateReqGson(baseReq);
            if (null == baseReq.getPageSize()) {
            	baseReq.setPageSize(10);
			}
            PageHelper.startPage(baseReq.getCurrentPage(), baseReq.getPageSize());
            DouyinUserInfoExample example = new DouyinUserInfoExample();
            example.createCriteria().andIsValidEqualTo(IsValidEnum.VALID_YES.getCode());
            List<DouyinUserInfo> douyinUserInfoList = douyinUserInfoDao.selectByExample(example);
            PageInfo<DouyinUserInfo> pageInfo = new PageInfo<DouyinUserInfo>(douyinUserInfoList);

            baseResp.setDouyinList(pageInfo.getList());
            baseResp.buildDefaultSuccessResp(baseReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("DouyinServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }

        log.info("queryVideoList.resp:{}", baseResp.toString());
        return baseResp.toString();
    }

    /**
     * 收藏
     *
     * @param reqStr
     * @return
     */
    @Override
    public String collectUser(String reqStr) {
        log.info("collectUser.req:{}", reqStr);
        BaseResp baseResp = new BaseResp();

        try {
            CheckParamUtils.validateReqString(reqStr);
            CollectUserReq baseReq = BaseDto.fromJson(reqStr, CollectUserReq.class);
            CheckParamUtils.validateReqGson(baseReq);
            
            DouyinCollect douyinCollect = new DouyinCollect();
            douyinCollect.setCollectNo(IdGenUtils.uuid());
            douyinCollect.setUserNo(baseReq.getUserNo());
            douyinCollect.setDouyinUserNo(baseReq.getDouyinUserNo());
            douyinCollect.setCollectedTime(new Date());
            douyinCollect.setCollectStatus(CollectStatusEnum.COLLECT_YES.getCode());
            douyinCollect.setCreatedTime(new Date());
            douyinCollect.setUpdatedTime(new Date());
            douyinCollectDao.insert(douyinCollect);

            baseResp.buildDefaultSuccessResp(baseReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("DouyinServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }
        log.info("collectUser.resp:{}", baseResp.toString());
        return baseResp.toString();

    }

    /**
     * 取消收藏
     *
     * @param reqStr
     * @return
     */
    @Override
    public String cancelCollectUser(String reqStr) {
        log.info("cancelCollectUser.req:{}", reqStr);
        BaseResp baseResp = new BaseResp();

        try {
            CheckParamUtils.validateReqString(reqStr);
            CancelCollectUserReq baseReq = BaseDto.fromJson(reqStr, CancelCollectUserReq.class);
            CheckParamUtils.validateReqGson(baseReq);
            
            DouyinCollectExample example = new DouyinCollectExample();
            DouyinCollect douyinCollect = new DouyinCollect();
            douyinCollect.setCollectNo(baseReq.getCollectNo());
            douyinCollect.setCollectStatus(CollectStatusEnum.COLLECT_CANCEL.getCode());
            douyinCollect.setUpdatedTime(new Date());
            douyinCollectDao.updateByExampleSelective(douyinCollect, example);

            baseResp.buildDefaultSuccessResp(baseReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("DouyinServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }
        log.info("cancelCollectUser.resp:{}", baseResp.toString());
        return baseResp.toString();
    }

    /**
     * 获取收藏列表
     *
     * @param reqStr
     * @return
     */
    @Override
    public String queryCollectList(String reqStr) {
        log.info("queryCollectList.req:{}", reqStr);
        QueryVideoListResp baseResp = new QueryVideoListResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            QueryCollectUserReq baseReq = BaseDto.fromJson(reqStr, QueryCollectUserReq.class);
            CheckParamUtils.validateReqGson(baseReq);

            if (null == baseReq.getPageSize()) {
            	baseReq.setPageSize(10);
    		}
            PageHelper.startPage(baseReq.getCurrentPage(), baseReq.getPageSize());
            DouyinCollectExample example = new DouyinCollectExample();
            example.createCriteria().andUserNoEqualTo(baseReq.getUserNo())
                    .andCollectStatusEqualTo(CollectStatusEnum.COLLECT_YES.getCode());
            example.setOrderByClause("created_time desc");

            List<DouyinCollect> collectLst = douyinCollectDao.selectByExample(example);
            PageInfo<DouyinCollect> pageInfo = new PageInfo<DouyinCollect>(collectLst);
            
            List<DouyinUserInfo> userInfoList = null;
            if (CollectionUtils.isNotEmpty(pageInfo.getList())) {
                userInfoList = new ArrayList<>();
                for (DouyinCollect collect : pageInfo.getList()) {
                    DouyinUserInfo douyinUserInfo = douyinUserInfoDao.selectByPrimaryKey(collect.getDouyinUserNo());
                    userInfoList.add(douyinUserInfo);
                }
            }

            baseResp.setDouyinList(userInfoList);
            baseResp.buildDefaultSuccessResp(baseReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("DouyinServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }
        log.info("queryCollectList.resp:{}", baseResp.toString());
        return baseResp.toString();
    }

    /**
     * 用户登录
     *
     * @param reqStr
     * @return
     */
    @Override
    public String userLogin(String reqStr) {
        log.info("userLogin.req:{}", reqStr);
        UserLoginResp UserLoginResp = new UserLoginResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            UserLoginReq userLoginReq = BaseDto.fromJson(reqStr, UserLoginReq.class);
            userLoginReq.setAppId(wxAppId);
            userLoginReq.setSecret(wxAppSecret);
            CheckParamUtils.validateReqGson(userLoginReq);
            if (!ProductCodeEnum.DOUYIN_VIDEO_CODE.getCode().equals(userLoginReq.getProductCode())) {
            	throw new CommonException(RespCodeEnum.PRODUCT_CODE_FAIL);
			}
            UserLoginResp = commUserService.userLogin(userLoginReq);
            if (UserLoginResp.isSuccess()) {
            	UserLoginResp.buildDefaultSuccessResp(userLoginReq);
			}
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("DouyinServiceImpl", reqStr, UserLoginResp, e.getMessage(), e);
        }
        log.info("userLogin.resp:{}", UserLoginResp.toString());
        return UserLoginResp.toString();
    }

    /**
     * 保存用户信息
     *
     * @param reqStr
     * @return
     */
    @Override
    public String saveUserInfo(String reqStr) {
        log.info("saveUserInfo.req:{}", reqStr);
        BaseResp baseResp = new BaseResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            SaveUserInfoReq saveUserInfoReq = BaseDto.fromJson(reqStr, SaveUserInfoReq.class);
            CheckParamUtils.validateReqGson(saveUserInfoReq);
            baseResp = commUserService.saveUserInfo(saveUserInfoReq);
			if (baseResp.isSuccess()) {
            	baseResp.buildDefaultSuccessResp(saveUserInfoReq);
			}
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("DouyinServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }
        log.info("saveUserInfo.resp:{}", baseResp.toString());
        return baseResp.toString();
    }

    /**
     * 查询用户是否解锁
     *
     * @param reqStr
     * @return
     */
    @Override
    public String queryUserUnlock(String reqStr) {
        log.info("queryUserUnlock.req:{}", reqStr);
//        RecordUseTimeResp recordUseTimeResp = new RecordUseTimeResp();
//        try {
//            CheckParamUtils.validateReqString(reqStr);
//            QueryUserUnlockReq queryUserUnlockReq = BaseDto.fromJson(reqStr, QueryUserUnlockReq.class);
//            CheckParamUtils.validateReqGson(queryUserUnlockReq);
//
//            //判断用户是否解锁
//            MosquitoUnlock mosquitoUnlock = queryUnlock(queryUserUnlockReq.getUserNo());
//            if (mosquitoUnlock == null) {
//
//                recordUseTimeResp.setIsOutTime(IsValidEnum.VALID_NO.getCode());
//                recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_NO.getCode());
//
//                MosquitoRecordTime recordTime = recordTimeDao.selectByPrimaryKey(queryUserUnlockReq.getUserNo());
//                if (recordTime != null) {
//                    recordUseTimeResp.setTime(recordTime.getUseTime().toString());
//                }
//
//            } else if (StringUtils.equals(mosquitoUnlock.getIsUnlock(), IsValidEnum.VALID_YES.getCode())) {
//                recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_YES.getCode());
//            } else {
//                recordUseTimeResp.setIsOutTime(IsValidEnum.VALID_YES.getCode());
//                recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_NO.getCode());
//            }
//
//            recordUseTimeResp.buildDefaultSuccessResp(queryUserUnlockReq);
//        } catch (Exception e) {
//            ExceptionUtils.buildExceptionResp("MosquitoServiceImpl", reqStr, recordUseTimeResp, e.getMessage(), e);
//        }
//        log.info("queryUserUnlock.resp:{}", recordUseTimeResp.toString());
//        return recordUseTimeResp.toString();
          return null;
    }

    /**
     * 修改用户分享次数
     * @param reqStr
     * @return
     */
	@Override
	public String updateUserShare(String reqStr) {
        log.info("updateUserShare.req:{}", reqStr);
        DouyinCollect dc  = new DouyinCollect();
        try{
            CheckParamUtils.validateReqString(reqStr);

        }catch (Exception e){

        }
		return null;
	}
}
